import path from 'path';

import { expect } from '@jest/globals';
import fs from 'fs-extra';
import * as fse from 'fs-extra';

import { buildAppAndCheckFile, buildAppAndHapsAndCheckFile, commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  },
};
const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.Sign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const rootPath = project.projectRootPath();
  const entryPath = project.getModule('entry').moduleRootPath();
  const libraryPath = project.getModule('shareLibrary').moduleRootPath();

  // 1.不配置enableSignTask直接构建App
  await buildAppAndHapsAndCheckFile(project, taskConfig, record);

  fs.readdirSync(path.join(rootPath, '.hvigor', 'report')).forEach((dir) => {
    // todo 读取read cache时间
    // console.log(dir);
  });

  const expDir = ['modules', 'other', 'plugins'];
  const cacheDir = path.join(entryPath, 'build', 'default', 'cache', 'default', 'default@CompileArkTS', 'esmodule', 'debug', 'compiler.cache');
  fs.readdirSync(cacheDir).forEach((dir: string, i: number) => {
    // todo 查看增量后修改时间是否跟上
    expect(dir).toEqual(expDir[i]);
    if (i === 0) {
      const expFile = ['EntryAbility.ets', 'Index.ets'];
      fs.readdirSync(path.join(cacheDir, expDir[i])).forEach((file, moduleIndex) => {
        expect(file).toContain(expFile[moduleIndex]);
      });
    }
  });
};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_BUILD_ROLLUP_CACHE_001')
  .description(
    `001、增量构建，read build package cache事件的耗时小于5ms
    另外，增量包含compiler.cache中间产物的检测`,
  )
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load(); // 流水线bat场景、命令行场景需手动测，用例仅保证构建结果正确
